<template>
  <div class="recent-conversations">
    <div class="back-button">
      <el-icon class="back-icon" @click="$router.go(-1)">
        <ArrowLeft />
      </el-icon>
    </div>

    <div class="header">
      <h1 class="title">最近对话</h1>
      <div class="actions">
        <el-tag type="info" class="record-hint" size="large">仅显示最新10条记录</el-tag>
        <el-checkbox v-model="isAllSelected" @change="handleSelectAll" :indeterminate="isIndeterminate">
          全选
        </el-checkbox>
        <el-button type="danger" :disabled="selectedConversations.length === 0" @click="batchDeleteConversations">
          批量删除 ({{ selectedConversations.length }})
        </el-button>
      </div>
    </div>

    <!-- 加载状态 -->
    <el-loading :loading="loading" />

    <div class="conversation-list">
      <div v-for="conversation in conversations" :key="conversation.aiConversationId" class="conversation-item">
        <el-checkbox v-model="conversation.selected" @change="handleSelectionChange(conversation)" />
        <div class="conversation-content" @click="selectConversation(conversation.aiConversationId)">
          <div class="conversation-header">
            <!-- 替换为显示 firstMessage -->
            <span class="conversation-id">消息: {{ conversation.firstMessage || "暂无消息" }}</span>
            <span class="conversation-time">{{ conversation.createTime }}</span>
          </div>
          <div class="conversation-preview">
            {{ conversation.remark || "暂无备注" }}
          </div>
        </div>
        <el-button type="danger" class="delete-button" @click.stop="deleteConversation(conversation.aiConversationId)">
          删除
        </el-button>
      </div>
    </div>

    <!-- 空状态 -->
    <el-empty v-if="conversations.length === 0" description="暂无对话" />
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { getConversationsByUserId, getConversationDetailAPI, deleteConversation as deleteConversationAPI } from '@/api/chat/index.js';
import { ArrowLeft } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';

export default {
  name: 'RecentConversations',
  components: {
    ArrowLeft
  },
  computed: {
    ArrowLeft() {
      return ArrowLeft;
    }
  },
  setup() {
    const router = useRouter();
    const conversations = ref([]);
    const selectedConversations = ref([]);
    const loading = ref(false);
    const isAllSelected = ref(false);
    const isIndeterminate = ref(false);

    // 修改获取对话列表的方法
    const fetchConversations = async () => {
      try {
        loading.value = true;
        const response = await getConversationsByUserId({
          pageNum: 1,
          pageSize: 10  // 固定只获取10条记录
        });

        if (response && response.code === 200) {
          const data = response.rows || [];
          conversations.value = data.map(conv => ({
            ...conv,
            selected: false,
            firstMessage: conv.firstMessage || "暂无消息"
          }));
        } else {
          ElMessage.error(response?.msg || '获取对话列表失败');
          conversations.value = [];
        }
      } catch (error) {
        console.error('获取对话列表失败:', error);
        ElMessage.error('获取对话列表失败');
        conversations.value = [];
      } finally {
        loading.value = false;
      }
    };

    // 选择对话
    const selectConversation = async (conversationId) => {
      try {
        console.log(`Fetching conversation details for ID: ${conversationId}`);
        const response = await getConversationDetailAPI(conversationId);
        console.log('Conversation details response:', response);

        if (response?.code === 200 && response.data) {
          const historyMessages = response.data.map(msg => {
            let parsedMessage;
            try {
              parsedMessage = JSON.parse(msg.messageContent);
            } catch (error) {
              console.error("JSON 解析失败:", error);
              parsedMessage = { message: msg.messageContent }; // 如果解析失败，使用原始内容
            }

            return {
              role: msg.sender === '2' ? 'user' : 'assistant',
              text: parsedMessage.message
            };
          });

          // 确保只在有有效消息时才更新对话记录
          if (historyMessages.length > 0) {
            localStorage.setItem('messages', JSON.stringify(historyMessages));
            localStorage.setItem('currentConversationId', conversationId);
            router.push({
              path: '/front/ai-tools',
              query: { fromRecent: 'true' }
            });
          } else {
            ElMessage.warning('没有找到相关的对话记录');
          }
        } else {
          ElMessage.error(response?.msg || '获取对话详情失败');
        }
      } catch (error) {
        console.error("获取对话详情失败", error);
        ElMessage.error("获取对话详情失败");
      }
    };

    // 处理选择变化
    const handleSelectionChange = (conversation) => {
      if (conversation.selected) {
        selectedConversations.value.push(conversation.aiConversationId);
      } else {
        const index = selectedConversations.value.indexOf(conversation.aiConversationId);
        if (index > -1) {
          selectedConversations.value.splice(index, 1);
        }
      }

      // 更新全选和半选状态
      const checkedCount = conversations.value.filter(conv => conv.selected).length;
      isAllSelected.value = checkedCount === conversations.value.length;
      isIndeterminate.value = checkedCount > 0 && checkedCount < conversations.value.length;
    };

    // 处理全选
    const handleSelectAll = (val) => {
      conversations.value.forEach(conv => {
        conv.selected = val;
      });

      if (val) {
        // 全选时，将所有对话的 ID 添加到选中列表
        selectedConversations.value = conversations.value.map(conv => conv.aiConversationId);
      } else {
        // 取消全选时，清空选中列表
        selectedConversations.value = [];
      }

      isIndeterminate.value = false;
    };

    // 删除对话
    const deleteConversation = async (conversationId) => {
      try {
        if (!conversationId) {
          ElMessage.error('对话ID不存在');
          return;
        }

        console.log('准备删除对话ID:', conversationId); // 添加调试信息

        await ElMessageBox.confirm('确定要删除这个对话吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        const response = await deleteConversationAPI(conversationId);

        console.log('删除对话响应:', response); // 添加调试信息

        if (response.code === 200) {
          ElMessage.success('删除成功');
          await fetchConversations();
        } else {
          ElMessage.error(response.msg || '删除失败');
        }
      } catch (error) {
        if (error === 'cancel') return;
        console.error('删除对话失败:', error);
        ElMessage.error('删除对话失败');
      }
    };

    // 批量删除
    const batchDeleteConversations = async () => {
      try {
        if (selectedConversations.value.length === 0) {
          ElMessage.warning('请选择要删除的对话');
          return;
        }

        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedConversations.value.length} 个对话吗？`,
          '批量删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );

        const deletePromises = selectedConversations.value.map(id =>
          deleteConversationAPI(id)
        );

        const results = await Promise.all(deletePromises);

        if (results.every(response => response.code === 200)) {
          ElMessage.success('批量删除成功');
          selectedConversations.value = [];
          await fetchConversations();
        } else {
          ElMessage.error('部分对话删除失败');
          await fetchConversations();
        }
      } catch (error) {
        if (error === 'cancel') return;
        console.error('批量删除失败:', error);
        ElMessage.error('批量删除失败');
      }
    };

    // 页面加载时获取对话列表
    onMounted(() => {
      fetchConversations();
    });

    return {
      conversations,
      selectedConversations,
      loading,
      handleSelectionChange,
      batchDeleteConversations,
      deleteConversation,
      selectConversation,
      ArrowLeft,
      isAllSelected,
      isIndeterminate,
      handleSelectAll,
    };
  }
};
</script>

<style scoped>
.recent-conversations {
  padding: 32px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #f8fafc;
  min-height: 100vh;
}

.back-button {
  margin-bottom: 32px;
}

.back-icon {
  font-size: 45px;
  color: #64748b;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.back-icon:hover {
  color: #334155;
  transform: translateX(-4px);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  padding: 0;
  position: relative;
}

.header::after {
  content: '';
  position: absolute;
  bottom: -16px;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(to right, #e2e8f0, transparent);
}

.title {
  font-size: 32px;
  font-weight: 700;
  color: #1e293b;
  margin: 0;
  letter-spacing: -0.5px;
}

.actions {
  display: flex;
  gap: 24px;
  align-items: center;
}

.conversation-list {
  background: #ffffff;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
}

.conversation-item {
  display: flex;
  align-items: center;
  padding: 24px;
  border-bottom: 1px solid #e2e8f0;
  gap: 24px;
  transition: all 0.3s ease;
}

.conversation-item:hover {
  background-color: #f8fafc;
  transform: translateX(4px);
  border-radius: 12px;
}

.conversation-item:last-child {
  border-bottom: none;
}

.conversation-content {
  flex: 1;
  cursor: pointer;
  padding: 12px;
  border-radius: 12px;
  transition: all 0.2s ease;
}

.conversation-content:hover {
  background-color: #f1f5f9;
}

.conversation-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.conversation-id {
  font-weight: 600;
  color: #334155;
  font-size: 16px;
}

.conversation-time {
  color: #64748b;
  font-size: 14px;
  font-weight: 500;
}

.conversation-preview {
  color: #475569;
  font-size: 14px;
  line-height: 1.6;
}

.pagination-container {
  margin-top: 40px;
  display: flex;
  justify-content: center;
}

:deep(.el-checkbox__label) {
  font-size: 14px;
  color: #334155;
  font-weight: 500;
}

.delete-button {
  font-size: 15px !important;
  padding: 12px 24px !important;
  height: auto !important;
}

:deep(.el-button) {
  border-radius: 10px;
  transition: all 0.3s ease;
  font-weight: 500;
}

:deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

:deep(.el-button.el-button--danger) {
  background: linear-gradient(135deg, #ff4d4d 0%, #f43f5e 100%);
  border: none;
  font-size: 15px;
  padding: 12px 24px;
  height: auto;
}

:deep(.el-empty) {
  padding: 48px 0;
}

.record-hint {
  margin-right: 16px;
  font-size: 16px !important;
  padding: 8px 16px !important;
  height: auto !important;
}

@media (max-width: 768px) {
  .recent-conversations {
    padding: 16px;
  }

  .conversation-item {
    padding: 16px;
  }

  .title {
    font-size: 24px;
  }

  .back-icon {
    font-size: 24px;
  }

  .delete-button {
    padding: 10px 20px !important;
    font-size: 6px !important;
  }

  .record-hint {
    font-size: 14px !important;
    padding: 6px 12px !important;
    margin-right: 8px;
  }
}
</style>